# Read Data of Range and Ephemeris from COM

import re
from tkinter import filedialog
import os
# 一行数据解析


# 伪距数据解析
def getRange(data):
    week = int(data[0])
    time = float(data[1])
    NumSate = int(data[2])
    rngList = data[3]
    rngList = rngList[0:-9].split(',')
    sateList = rngList[0:NumSate*10:10];
    rngMat = []
    for ii in range(1,33):
        try:
            idx = sateList.index(str(ii))           # 没有考虑同一卫星多个伪距的情况
            rngMat.append(float(rngList[idx*10+2]))
            rngMat.append(float(rngList[idx*10+3]))
        except :
            rngMat.append(0)
            rngMat.append(0)
    return [week,time,NumSate,rngMat]


# 星历数据解析
def getEphm(data):
    PRN = int(data[2])
    data = data[3].split(",")
    SatellateTable[PRN-1] = data[0:28]
    return

# Main CMD
init_dir = os.getcwd()
filename = filedialog.askopenfilename(initialdir=init_dir, title="Select files", filetypes=[('all text files', '.txt')])
fileRng = "RANGE.txt"
fileEPM = "EPHEMERIS.txt"
fobj = open(filename,"r")
fR = open(fileRng,"w")
fE = open(fileEPM,"w")
SatellateTable = [[0] * 28 for i in range(32)]

for line in fobj.readlines():
    head = line[0:4]
    if head=="#GPS":
        searchStr = re.findall( r'#GPSEPHEMA,COM2,.*?,FINESTEERING,(.*?),(.*?),.*?;(.*?),(.*?)\n', line, re.S)
        getEphm(searchStr[0])
        
    elif head=="#RAN":
        searchStr = re.findall( r'#RANGEA,COM2,0,.*?,FINESTEERING,(.*?),(.*?),.*?;(.*?),(.*?)\n', line, re.S)
        RNGData = getRange(searchStr[0])
        inputStr = str(RNGData[0])+' '+str(RNGData[1])+' '+str(RNGData[2])+' '
        fR.write(inputStr)
        for iSate in RNGData[3]:
            inputStr = str(iSate)+' '
            fR.write(inputStr)
        fR.write("\n")
    else:
        print("error")

for iSate in SatellateTable:
        for para in iSate:
            fE.write(str(para)+" ")
        fE.write("\n")
fobj.close()
fR.close()
fE.close()

